/**
 * Created by Administrator on 2018/4/5.
 */
var totalNum = 1;  //总题数
var currentNum = 1; //当前题数
var showTimuNumTime = 1000;    //题数显示时间  毫秒
var showDetaiTime = 1000;    //题数显示时间  毫秒
var gameTime = 10;  //答题时间10S
var cacheTime = 1; //缓冲时间
var countdownTime;  //答题计时器
var popUpTime = 2000;   //弹框延时 毫秒

var js_config = {};
layui.use(['layer'], function () {
    var layer = layui.layer;

    /**
     * 初始化页面
     */
    function initPage() {
        var token = sessionStorage.access_token;
        if(token==null){
            againToken();
            return;
        }
        $('.pop-up-box').unbind('click');
        var vue = new Vue({
            el: '#index_div',
            data: {
                user_info: {},   //答题者信息
                challenge_info: {}, //挑战详情
                challenge_id: 0,    //挑战id
                answer_log_id: 0,    //本次答题id
                problem_option_list: {},  //问题选项
                problem_title: '',   //问题标题
                topic_id: 0,     //问题id
                option_id: 0,    //提交选项id
            },
            watch: {},
            methods: {

            },
            filters: {
                integral: function (value) {
                    return parseInt(value);
                },
                getChar: function (val) {
                    return String.fromCharCode(65 + val);
                }
            }
        });
        function getChar(val){
            return String.fromCharCode(65 + val);
        }
        function initId() {
            var challenge_id = getQueryString('challenge_id');
            var answer_log_id = getQueryString('answer_log_id');
            if (!challenge_id || !answer_log_id) {
                console.log('对不起，您没有答题');
            } else {
                vue.challenge_id = challenge_id;
                vue.answer_log_id = answer_log_id;
                initChallengeInfo();
            }
        }

        function initChallengeInfo() {
            var data = {
                token: token,
                red_envelope_id: vue.challenge_id
            }
            $.ajax({
                type: "post"
                , url: '/index/challenge/ajax_challenge_detail'
                , data: data
                , async: false
                , success: function (result) {
                    console.info(result);
                    if (result.code == -1) {
                        window.location.href = 'index.html';
                        //layer.msg(result.msg, function () {
                        //
                        //});
                    }
                    if (result.code == 0) {
                        againToken();
                        return;
                    }
                    if (result.code == 1) {
                        vue.challenge_info = result.data;
                        totalNum = vue.challenge_info.topic_number;
                        startAnswer();
                    }
                }
                , error: function (resq) {
                    console.info(resq);
                    layer.msg("服务器异常");
                }
            });
        }

        /**
         * 初始化JS-SDK配置信息
         */
        function initJsConfig() {

            console.log(user_id);
            var data = {
                token: token,
                url:window.location.href
            }
            $.post("/index/config/ajax_get_wechat_js", data, function (result) {
                //if (result.code == -1) {   //失败
                //    layer.msg(result.msg);
                //    return;
                //}
                if (result.code == 0) { //Token失效
                    againToken();
                    return;
                }
                if (result.code == 1) { //成功
                    vue.js_config = result.data;
                    js_config = vue.js_config;
                    console.log(js_config);
                    startJsSDK();
                }

            });
        }

        initUserInfo(vue, token);    //初始化答题者信息
        initId();
        initJsConfig();

        function initPopupHeight() {
            var acH = $('.answer-correct-box').outerHeight();
            $('.answer-correct-box').css('marginTop', (winH - acH) * 0.45 + 'px');

            var arH = $('.answer-error-box').outerHeight();
            $('.answer-error-box').css('marginTop', (winH - arH) * 0.45 + 'px');
        };

        /**
         * 挑战成功,弹出框
         */
        function showAnswerCorrect() {
            setTimeout(function () {
                $('#answer_correct_pop_up').show();
                $('html,body').addClass('ovfHiden'); //使网页可滚动
                initPopupHeight();
            }, popUpTime);
        }

//            $('.answer-correct-box').click(function (e) {
//                e.stopPropagation();
//            });

        /**
         * 挑战失败,弹出框
         */
        function showAnswerError() {
            setTimeout(function () {
                $('#answer_error_pop_up').show();
                $('html,body').addClass('ovfHiden'); //使网页可滚动
                initPopupHeight();
            }, popUpTime);
        }

//            $('.answer-error-box').click(function (e) {
//                e.stopPropagation();
//            });

        /**
         * 开始答题
         */
        function startAnswer() {
            vue.option_id = 0;
            clearOptionClass(); //清除选项样式
            setProgress();  //设置进度条
            showCurrentNum();   //显示当前题目
        }

        /**
         *  清除选项样式
         */
        function clearOptionClass(){
            $('.key-item').removeClass('correct');
        }

        /**
         * 设置进度条
         */
        function setProgress() {
            var pW = currentNum / totalNum * 100;
            $('.progress').width(pW + '%');
        }

        /**
         * 显示当前题数
         */
        function showCurrentNum() {
            $('.show-answer-num-box').find('span').html('第' + currentNum + '题');
            if (currentNum == totalNum) {
                $('.show-answer-num-box').find('span').html('最后一题');
            }

            $('.show-answer-num-box').show();

            //两秒后显示题目
            setTimeout(function () {
                $('.show-answer-num-box').hide();
                showAnswerTimu();
            }, showTimuNumTime);
        }

        /**
         * 获取问题详情
         */
        function getProblemDetail() {
            var data = {
                token: token,
                answer_log_id: vue.answer_log_id
            }
            $.ajax({
                type: "post"
                , url: '/index/challenge/ajax_start_answer'
                , data: data
                , async: false
                , success: function (result) {
                    console.info(result);
                    if (result.code == -1) {    //题目获取失败
                        layer.msg(result.msg, function () {
                            window.location.href = 'index.html';
                        });
                        return;
                    }
                    if (result.code == 0) {
                        console.log('token失效');
                        againToken();
                        return;
                    }
                    if (result.code == 1) {
                        vue.topic_id = result.data.topic_id;
                        vue.problem_title = result.data.title;  //问题标题
                        vue.problem_option_list = result.data.option_list;  //选项列表

                        var html = '';
                        $(result.data.option_list).each(function(index,value){

                            var char = getChar(index);
                            html += '<div class="key-item"  data-id="'+value.id+'" >';
                            html += '<span class="symbol">'+char+'</span>';
                            html += '<span>'+value.content+'</span>';
                            html += '</div>';
                        });
                        $('.answer-detail-keys-box').html(html);

                    }
                }
                , error: function (resq) {
                    console.info(resq);
                    layer.msg("服务器异常");
                }
            });
        }

        /**
         * 显示题目
         */
        function showAnswerTimu() {

            getProblemDetail(); //获取问题详情
            $('.start-answer-detail-num').html('第' + currentNum + '题');
            $('.start-answer-detail-box').show();

            //显示答案
            setTimeout(function () {
                showAnswerDetail();
            }, showDetaiTime);
        }

        //显示答案
        function showAnswerDetail() {
            $('.answer-detail-keys-box').show();
            startTime();
            bindKeyItemClick();
        }

        //开启答题计时器
        function startTime() {
            var gametime = gameTime;
            $('.end-time').html('9');
            $('.end-time').show();
            countdownTime = setInterval(function () {
                gametime--;
//                    console.log(gametime);
                $('.end-time').html(gametime);

                //答题结束
                if (gametime == 0) {
                    clearInterval(countdownTime);
                    //未答题
                    unBindKeyItemClick();
                    notAnswer();
                }
            }, 1000);
        }

        /**
         * 缓存计时器
         */
        function cachecountdownTime() {
            var gametime = cacheTime;
            $('.end-time').show();
            var cachedownTime = setInterval(function () {
                gametime--;
//                    console.log(gametime);
                $('.end-time').html(gametime);

                //缓冲结束
                if (gametime == 0) {
                    clearInterval(cachedownTime);
                    hideAnswerContent();
                    startAnswer();
                }
            }, 1000);
        }

        /**
         * 提交答案
         */
        function submitAnswer() {
            var data = {
                token: token,
                answer_log_id: vue.answer_log_id,
                topic_id: vue.topic_id,
                option_id: vue.option_id
            }


            //提交答案
            $.ajax({
                type: "post"
                , url: '/index/challenge/ajax_submit_answer'
                , data: data
                , async: false
                , success: function (result) {
                    console.info(result);
                    if (result.code == -1) {    //提交失败，结束回答
                        //layer.msg(result.msg, function () {
                        //    window.location.href = 'index.html';
                        //});
                    }
                    if (result.code == 0) {
                        againToken();
                        return;
                    }
                    if (result.code == 1) {
                        if (result.data.success) {    //回答正确
                            $('.key-item').each(function () {
                                if ($(this).hasClass('click')) {
                                    $(this).removeClass('click').addClass('correct');
                                }
                            })
                            if (result.data.is_complete) {    //答题结束
                                showAnswerCorrect();
                            } else {
                                cachecountdownTime();   //下一题，缓存器
                                currentNum++;   //当前题数
                            }
                        } else { //回答错误
                            $('.key-item').each(function () {
                                if ($(this).hasClass('click')) {
                                    $(this).removeClass('click').addClass('error');
                                }
                            })

                            $('.key-item[data-id=' + result.data.right_option_id + ']').addClass('correct');    //显示正确答案，添加样式
                            showAnswerError();
                        }
                    }
                }
                , error: function (resq) {
                    console.info(resq);
                    layer.msg("服务器异常");
                }
            });
        }


        /**
         *  绑定鼠标点击事件，回答问题
         */
        function bindKeyItemClick() {

            //添加答案点击事件
            $('.key-item').click(function () {
                vue.option_id = $(this).data('id');
                unBindKeyItemClick();
                //添加点击样式，移除点击
                $(this).addClass('click');
                console.log($('.key-item').eq($(this).index()).data('id'));
                console.log('click'+vue.option_id);
                //停止答题倒计时
                clearInterval(countdownTime);

                submitAnswer();
            });
        }

        /**
         * 取消答案点击事件
         */
        function unBindKeyItemClick() {
            $('.key-item').unbind('click');
        }

        /**
         * 隐藏题目信息
         */
        function hideAnswerContent() {
            $('.end-time').hide();
            $('.start-answer-detail-box').hide();
            $('.answer-detail-keys-box').hide();
        }

        /**
         * 未答题，提交，进行回显
         */
        function notAnswer() {
            submitAnswer();
            showAnswerError();
        }
    }

    /**
     * 初始化完成加载函数
     */
    $(function () {
        initGlobalPage();
        initPage();
    });
});
